package de.nibian.minecraft.plotRequest;

import java.io.*;
import java.util.*;

public class dateienVerarbeiten {
	private boolean error;

	public dateienVerarbeiten(){
		error = false;
	}

	public Properties propsAuslesen(String propFile){
		if(error == false){
			Properties prop = new Properties();
			InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFile);
			try {
				prop.load(inputStream);
			} catch (IOException e) {
				if(dateiErzeugen(propFile) == true){
					error = false;
					zeileErgaenzen(propFile, "#Nibian.de");
					zeileErgaenzen(propFile, "");
					zeileErgaenzen(propFile, "#MySQL");
					zeileErgaenzen(propFile, "Host=localhost");
					zeileErgaenzen(propFile, "Port=3306");
					zeileErgaenzen(propFile, "Database=minecraftplots");
					zeileErgaenzen(propFile, "User=minecraftplots");
					zeileErgaenzen(propFile, "Password=12345678");
					zeileErgaenzen(propFile, "Prefix=mp_");
					propsAuslesen(propFile);
				}else{
					error = true;
				}
			}
		}

		return null;
	}
	private boolean dateiErzeugen(String Filename){
		File file = new File(Filename);
		if (file != null) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				System.err.println("Error creating " + file.toString());
			}
			if (file.isFile() && file.canWrite() && file.canRead())
				return true;
		}
		return false;
	}
	private void zeileErgaenzen(String Filename, String Text){
		try{
			File file =new File(Filename);

			//if file doesnt exists, then create it
			if(!file.exists()){
				file.createNewFile();
			}
			//true = append file
			FileWriter fileWritter = new FileWriter(file.getName(),true);
			BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
			bufferWritter.write(Text);
			bufferWritter.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	public String dateiAuslesen(String Filename){
		File file = new File(Filename);
		String meinString = null;
		try {
			BufferedReader in = new BufferedReader (
					new FileReader (file) );
			try {
				while( (meinString = in.readLine()) != null ) {
					System.out.println(meinString);
				}
				in.close();
			} catch (IOException e) {
				System.out.println("Read error " + e);
			}
		} 
		catch (IOException e) {
			System.out.println("Open error " + e);
		}
		return meinString;
	}
}